package cn.zhaoyuening.zshop4j.manager.web;

import cn.zhaoyuening.zshop4j.common.bean.EasyUiListResult;
import cn.zhaoyuening.zshop4j.common.bean.ZShop4jResponceResult;
import cn.zhaoyuening.zshop4j.common.constant.ReturnResult;
import cn.zhaoyuening.zshop4j.manager.service.ItemService;
import cn.zhaoyuening.zshop4j.manager.pojo.TbItem;
import cn.zhaoyuening.zshop4j.common.utils.JsonUtils;
import com.alibaba.dubbo.common.json.JSON;
import com.sun.tracing.dtrace.ModuleAttributes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Zhao on 2017/4/3.
 */
@Controller
public class ItemController {
    private ItemService itemService;

    @Autowired
    public void setItemService(ItemService itemService) {
        this.itemService = itemService;
    }

    @RequestMapping(value = "item/{id}",method = RequestMethod.GET,produces = "text/plain; charset=utf-8")
    @ResponseBody
    public String findById(@PathVariable("id") Long id) {
        TbItem item = itemService.findById(id);
        String jsonData = JsonUtils.objectToJson(item);
        return jsonData;
    }

    @RequestMapping(value = "items",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String findAllByPage(@RequestParam("page") Integer pageNum, @RequestParam("rows") Integer pageSize) {
        EasyUiListResult<TbItem> itemEasyUiListResult = itemService.findAllByPage(pageNum, pageSize);
        String itemsJsonData = JsonUtils.objectToJson(itemEasyUiListResult);
        return itemsJsonData;
    }

    @RequestMapping(value = "item/{id}",method = RequestMethod.DELETE,produces = "text/plain; charset=utf-8")
    @ResponseBody
    public String deleteById(@PathVariable("id") Long id) {
        int result = itemService.deleteById(id);
        if (result >= 1) {
            return ReturnResult.SUCCESS;
        }
        return ReturnResult.ERROR;
    }

    @RequestMapping(value = "item", method = RequestMethod.POST, produces = "text/plain; charset=utf-8")
    @ResponseBody
    public String insertItem(TbItem item, String desc) {
        ZShop4jResponceResult result = itemService.addItem(item, desc);
        return JsonUtils.objectToJson(result);
    }

}
